//
//  CMFPhoneNumCtrl.m
//  CreditManger
//
//  Created by 于会海 on 15/11/2.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CMFPhoneNumCtrl.h"
#import "CMFVerCodeCtrl.h"
#import "UIImageView+WebCache.h"
#import "CMGetRegMobileCodeInfo.h"
#import "CMGetRegMobileCodeParam.h"
#import "CMGetRegMobileCodeParser.h"
#import "CheckValid.h"
@interface CMFPhoneNumCtrl ()<UITextFieldDelegate>


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topBackViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topBackViewY;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumber;
@property (weak, nonatomic) IBOutlet UIView *topBackView;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
- (IBAction)nextBtnClicked:(UIButton *)sender;

@property (strong, nonatomic) UIImageView* codeImageView;
@property (strong, nonatomic) UITextField* graphCode;
@property (assign, nonatomic) BOOL isBack;
@end

@implementation CMFPhoneNumCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)buildLayout{
    
    self.navigationController.navigationBarHidden = NO;
    self.title = @"找回密码";
    if (self.isModify)
    {
        self.title = @"修改密码";
    }
    self.nextBtn.layer.cornerRadius = 4.0;
    self.phoneNumber.delegate = self;
    self.phoneNumber.keyboardType = UIKeyboardTypeNumberPad;
}

- (void)setCodeImageViewWithCode
{
    NSString* gid = [self getGID];
    NSMutableString* urlString =  [[NSMutableString alloc] init];
    [urlString appendFormat:@"%@gid=%@",@"http://192.168.50.222:6088/koudai_server/user/getPwdImageCode.do?",gid];
    LLog(@"%@",urlString);
    [self.codeImageView setImageWithURL:[NSURL URLWithString:urlString]  placeholderImage:nil options:SDWebImageRefreshCached];
}

- (NSString*)getGID
{
    NSUUID *identifierForVendor = [[UIDevice currentDevice] identifierForVendor];
    NSString *deviceId = [identifierForVendor UUIDString];
    return deviceId;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"])
    {
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if (self.phoneNumber == textField)
    {
        if ([toBeString length] > 10){
            textField.text = [toBeString substringToIndex:11];
            [textField resignFirstResponder];
            return NO;
        }
    }
    if (self.graphCode == textField)
    {
        if ([toBeString length] > 5) {
            return NO;
        }
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma AlertView SHOW
- (void)showPhoneNumAlert
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"输入手机号码有误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
- (void)showGraphAlert
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"图形验证码输入有误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)addNewGraphCodeView{
    
    if (!self.isBack) {
        self.isBack = YES;
    }else{
        return;
    }
    
    self.topBackViewY.constant = 10.0;
    self.topBackViewHeight.constant = 82;
    
    UIView* midLine = [[UIView alloc] initWithFrame:CGRectMake(10, 40, SCREEN_WIDTH-10, 1)];
    midLine.backgroundColor = [LCCommon getColor:@"cccccc"];
    [self.topBackView addSubview:midLine];
    
    UIImage* graImage = [UIImage imageNamed:@"regist_graphCode"];
    UIImageView* graphImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 52, graImage.size.width, graImage.size.height)];
    graphImage.image = graImage;
    [self.topBackView addSubview:graphImage];
    
    self.graphCode = [[UITextField alloc] initWithFrame:CGRectMake(38, 42, 200, 40)];
    self.graphCode.font = [UIFont systemFontOfSize:12];
    self.graphCode.placeholder = @"请输入图形验证码";
    self.graphCode.delegate = self;
    [self.topBackView addSubview:self.graphCode];
    
    UIButton* reGraphBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    reGraphBtn.frame = CGRectMake(SCREEN_WIDTH - 60, 44, 50, 35);
    reGraphBtn.tintColor = [LCCommon getColor:@"666666"];
    [reGraphBtn setTitle:@"换一张" forState:UIControlStateNormal];
    [reGraphBtn addTarget:self action:@selector(reGraphBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.topBackView addSubview:reGraphBtn];
    
    UIView* rgtBackView = [[UIView alloc] initWithFrame:CGRectMake(reGraphBtn.frame.origin.x-70-5, 49, 70, 24)];
    rgtBackView.layer.borderColor = [LCCommon getColor:@"cccccc"].CGColor;
    rgtBackView.layer.borderWidth = 1;
    [self.topBackView addSubview:rgtBackView];
    
    
    self.codeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, rgtBackView.bounds.size.width, rgtBackView.bounds.size.height)];
    [self setCodeImageViewWithCode];
    [rgtBackView addSubview:self.codeImageView];
    
    UIView* rgtLine = [[UIView alloc] initWithFrame:CGRectMake(rgtBackView.frame.origin.x-10
                                                               , 41, 1, 40)];
    [rgtLine setBackgroundColor:[LCCommon getColor:@"cccccc"]];
    [self.topBackView addSubview:rgtLine];
    
}

#pragma mark buttonClicked
- (void)reGraphBtnClicked:(UIButton*) button{
    [self setCodeImageViewWithCode];
}

- (IBAction)nextBtnClicked:(UIButton *)sender {
    
    CMGetRegMobileCodeParam* param = [[CMGetRegMobileCodeParam alloc] init];
    param.mobile = self.phoneNumber.text;
    param.gid = [self getGID];

    if (self.phoneNumber.text.length < 11){
        [self showPhoneNumAlert];
        return;
    }
    if(![CheckValid isValidatePhone:self.phoneNumber.text]){
        [self.phoneNumber becomeFirstResponder];
        DISSMISS_ERRView(@"手机号输入不正确",[[[UIApplication sharedApplication] windows] lastObject]);
        return;
    }
    if (self.isBack == YES) {
        if (self.graphCode.text.length < 4) {
            [self  showGraphAlert];
            return;
        }
        param.imageCode = self.graphCode.text;
    }else{
        param.imageCode = @"";
    }

    CMGetRegMobileCodeParser* parser = [[CMGetRegMobileCodeParser alloc] init];
    [NetCenter postDataFromURL:Method_getPwdMobileCode params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            CMGetRegMobileCodeInfo* info = (CMGetRegMobileCodeInfo*)myResult.result;
            CMFVerCodeCtrl* verCodeVC = [[CMFVerCodeCtrl alloc] init];
            verCodeVC.vercode = info.mobileCode;//这个需要在上线前取消
            verCodeVC.phoneNumber = self.phoneNumber.text;
            verCodeVC.isModify = self.isModify;
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(addNewGraphCodeView)
                                                         name:@"addGraph"
                                                       object:nil];
            [self.navigationController pushViewController:verCodeVC animated:YES];
 
        }else if(myResult.code == 1){
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR(error.description);
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.phoneNumber.text = @"";
    self.graphCode.text = @"";
    if(self.isBack == YES){
        [self setCodeImageViewWithCode];
    }
    self.navigationController.navigationBarHidden = NO;
}
@end
